<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\common\logic\admin;

use app\common\model\TemplateGroupModel;
use app\common\model\TemplateHeaderModel;
use app\common\model\TemplateModel;
use app\common\model\TemplateFooterModel;
use app\common\model\TemplateCategoryModel;

class TemplateGroup
{
	private $mTemplateGroup;
	public function __construct(){
		$this->mTemplateGroup = new TemplateGroupModel();
	}
	public function save($param,$status = 1){
		
		if(!empty($param['post']['header_id'])){
			$data = TemplateHeaderModel::get($param['post']['header_id']);
			if (empty($data)) {
				return [
						'code'=>0,
						'msg'=>'表头ID不存在'
					];
			}else{
				if($data['status'] == 2){
					return [
						'code'=>0,
						'msg'=>'该表头模板未启用'
					];
				}
			}
		}
		if(!empty($param['post']['template_id'])){
			$data = TemplateModel::get($param['post']['template_id']);
			if (empty($data)) {
				return [
						'code'=>0,
						'msg'=>'课题ID不存在'
					];
			}else{
				if($data['status'] == 0){
					return [
						'code'=>0,
						'msg'=>'该课题模板未启用'
					];
				}
			}
		}
		if(!empty($param['post']['footer_id'])){
			$data = TemplateFooterModel::get($param['post']['footer_id']);
			if (empty($data)) {
				return [
						'code'=>0,
						'msg'=>'表尾ID不存在'
					];
			}else{
				if($data['status'] == 2){
					return [
						'code'=>0,
						'msg'=>'该表尾模板未启用'
					];
				}
			}
		}
		$param['post']['p_category_id'] = TemplateCategoryModel::where('category_id',$param['post']['category_id'])->value('p_category_id');

		switch ($status) {
			case 1:
				$rs = $this->mTemplateGroup->save($param['post']);
				break;
			case 2:
				$rs = $this->mTemplateGroup->save($param['post'],['group_id'=>$param['group_id']]);
				break;

		}
		if ($rs) {
			return [
					'code'=>1,
				];
		}else{
			return [
					'code'=>0,
					'msg'=>'添加失败'
				];
		}
		
	}
}